package com.sky.service.Impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper bookMapper;

//    新增地址
    @Override
    public Integer save(AddressBook addressBook) {
        Long Id = BaseContext.getCurrentId();
        addressBook.setUserId(Id);
        List<AddressBook> all = bookMapper.getAll();
        if(all != null){
            addressBook.setIsDefault(1);
        }else {
            addressBook.setIsDefault(0);
        }
        Integer save = bookMapper.save(addressBook);
        return save;
    }

    //    查询当前登录用户的所有地址信息
    @Override
    public List<AddressBook> getAll() {
        List<AddressBook> all = bookMapper.getAll();
        return all;
    }

//    查询默认地址
    @Override
    public AddressBook getDefault() {
        Long Id = BaseContext.getCurrentId();
        AddressBook aDefault = bookMapper.getDefault(Id);
        return aDefault;
    }


//    根据id修改地址
    @Override
    public Integer updateById( AddressBook addressBook) {
        Integer integer = bookMapper.updateById(addressBook);
        return integer;
    }

//    根据id删除地址
    @Override
    public Integer deleteById(Long id) {
        Integer integer = bookMapper.deleteById(id);
        return integer;
    }


//    根据id查询地址
    @Override
    public AddressBook seleteById(Long id) {
        AddressBook addressBook = bookMapper.seleteById(id);
        return addressBook;
    }

//    设置默认地址
    @Override
    public Integer updateDefault(AddressBook addressBook) {

        List<AddressBook> all = bookMapper.getAll();
        List<AddressBook> collect = all.stream().filter(s -> s.getIsDefault() == 0).collect(Collectors.toList());

        if(collect != null){
            for (AddressBook b : collect) {
                Long id = b.getId();
                bookMapper.updateDefaultById(id,1);
            }
        }

        addressBook.setIsDefault(0);
        Integer integer = bookMapper.updateDefault(addressBook);
        return integer;
    }

}
